// pages/user/user-page.js
import { RequestManager } from '../../util/requestManager.js'
let requestManager = new RequestManager()
const app = getApp()

import { DBManager } from '../../util/dbManager.js'
let dbManager = new DBManager()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    conentMarginTop: 0,
    canLogin:false,
    userInfo:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      canLogin: app.globalData.userInfo === null ? true :false,
      userInfo: app.globalData.userInfo,
      conentMarginTop: app.globalData.navHeight
    })
  },

  //  分享给好友
  onShareAppMessage: function () {
    return app.public_getShareInfo()
  },

  //
  action_user_register:function(){
    //  注册
    wx.navigateTo({
      url: '/pages/user/user-register-page',
    })
  },
  private_getUserInfo: function (result) {

    let userInfo = result.detail.userInfo;
    if(userInfo != null) {
      //  用户授权登录之后的操作
      app.saveWXUserInfo(userInfo)

      let nickName = userInfo.nickName
      let head = userInfo.avatarUrl
      var that = this;
      requestManager.userRegister(app.globalData.openid, nickName, head, (reslut) => {
      });

      this.setData({
        canLogin: false,
        userInfo: userInfo
      })
    } 
  },
  private_previewImage: function (imagePath) {
    wx.previewImage({
      current: imagePath,
      urls: [imagePath]
    })
    wx.hideLoading();
  },
  action_share: function () {

    wx.showLoading({
      title: '正在生成小程序码',
    })
    
    var that = this;
    //  生成一张分销的小程序码
    let imagePath = app.globalData.share_codeFileId;
    if (imagePath == null) {
      //需要去生成一张小程序码
      var scene = "id=" + app.globalData.openid;
      wx.cloud.callFunction({
        name: 'getQRCode',
        data: {
          page: 'pages/index/index-page',
          width: '360',
          scene: scene
        },
        success: res => {
          var fileInfo = res.result[0];
          var fileId = fileInfo.fileID;
          dbManager.updateQRCodeFileID(app.globalData.openid, fileId);

          that.private_previewImage(fileId);
          app.globalData.share_codeFileId = fileId;
        },
        fail: error => {
          console.log('云函数生成图片失败', error)
        }
      })
    }
    else {
      this.private_previewImage(imagePath);
    }
  }
})